﻿// ----------------------------------------------------------------------------------
// Microsoft Developer & Platform Evangelism
// 
// Copyright (c) Microsoft Corporation. All rights reserved.
// 
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
// EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
// OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
// ----------------------------------------------------------------------------------
// The example companies, organizations, products, domain names,
// e-mail addresses, logos, people, places, and events depicted
// herein are fictitious.  No association with any real company,
// organization, product, domain name, email address, logo, person,
// places, or events is intended or should be inferred.
// ----------------------------------------------------------------------------------

namespace Microsoft.Samples.WindowsPhoneCloud.Phone.ViewModel
{
    using System;
    using System.Collections.Generic;
    using System.Collections.ObjectModel;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Threading;
    using Microsoft.Phone.Shell;
    using Microsoft.Samples.WindowsPhoneCloud.StorageClient;

    public class ListBlobsPageViewModel : PivotItemViewModel
    {
        private const string IconsRootUri = "/Toolkit.Content/";

        private readonly ICloudBlobClient blobClient;
        private readonly Dispatcher dispatcher;

        private bool isListing = false;
        private bool hasResults = true;
        private bool useFlatBlobListing = false;
        private string prefix = string.Empty;
        private string message = string.Empty;

        public ListBlobsPageViewModel()
            : this(App.CloudClientFactory.ResolveCloudBlobClient("UploadAndList"), Deployment.Current.Dispatcher)
        {
        }

        public ListBlobsPageViewModel(ICloudBlobClient blobClient, Dispatcher dispatcher)
        {
            this.blobClient = blobClient;
            this.dispatcher = dispatcher;
            this.CloudBlobs = new ObservableCollection<ICloudBlob>();
        }

        public event EventHandler<EventArgs> TakePhoto;

        public ObservableCollection<ICloudBlob> CloudBlobs { get; set; }

        public bool IsListing
        {
            get
            {
                return this.isListing;
            }

            set
            {
                if (this.isListing != value)
                {
                    this.isListing = value;
                    this.NotifyPropertyChanged("IsListing");
                }
            }
        }

        public string Message
        {
            get
            {
                return this.message;
            }

            set
            {
                if (this.message != value)
                {
                    this.message = value;
                    this.NotifyPropertyChanged("Message");
                }
            }
        }

        public bool HasResults
        {
            get
            {
                return this.hasResults;
            }

            set
            {
                if (this.hasResults != value)
                {
                    this.hasResults = value;
                    this.NotifyPropertyChanged("HasResults");
                }
            }
        }

        public string Prefix
        {
            get
            {
                return this.prefix;
            }

            set
            {
                if (this.prefix != value)
                {
                    this.prefix = value;
                    this.NotifyPropertyChanged("Prefix");
                }
            }
        }

        public bool UseFlatBlobListing
        {
            get
            {
                return this.useFlatBlobListing;
            }

            set
            {
                if (this.useFlatBlobListing != value)
                {
                    this.useFlatBlobListing = value;
                    this.NotifyPropertyChanged("UseFlatBlobListing");
                }
            }
        }

        public void ListBlobs()
        {
            this.IsListing = true;
            this.Message = "Listing blobs...";
            try
            {
                this.blobClient.ListBlobsWithPrefix(
                    this.Prefix,
                    this.UseFlatBlobListing,
                    r =>
                    {
                        if (this.dispatcher != null)
                        {
                            this.dispatcher.BeginInvoke(() => this.UpdateListBlobs(r));
                        }
                        else
                        {
                            this.UpdateListBlobs(r);
                        }
                    });
            }
            catch (Exception exception)
            {
                var errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message;

                this.IsListing = false;
                this.Message = string.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage);
            }
        }

        protected override void PopulateApplicationBarButtons(IApplicationBar applicationBar)
        {
            var takePictureButton = new ApplicationBarIconButton(new Uri(string.Format(CultureInfo.InvariantCulture, "{0}{1}", IconsRootUri, "appbar.feature.camera.rest.png"), UriKind.Relative)) { Text = "take picture" };
            takePictureButton.Click += (s, e) => this.RaiseTakePhoto();

            applicationBar.Buttons.Add(takePictureButton);
        }

        private void UpdateListBlobs(CloudOperationResponse<IEnumerable<ICloudBlob>> result)
        {
            if (result.Exception == null)
            {
                this.CloudBlobs.Clear();
                foreach (var blob in result.Response)
                {
                    this.CloudBlobs.Add(blob);
                }

                this.HasResults = this.CloudBlobs.Count > 0;
                this.Message = "Listing finished successfully.";
            }
            else
            {
                this.Message = string.Format(CultureInfo.InvariantCulture, "Error: {0}", result.Exception.Message);
            }
            
            this.IsListing = false;
        }
        
        private void RaiseTakePhoto()
        {
            var takePhoto = this.TakePhoto;
            if (takePhoto != null)
            {
                takePhoto(this, new EventArgs());
            }
        }
    }
}
